package com.netcracker.ui.servlet;

import com.netcracker.ui.helper.UIHelper;
import com.netcracker.ui.command.Command;
import java.io.IOException;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name="ViewController", urlPatterns={"/", "/Library"})
public class ViewController extends HttpServlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(ViewController.class);

    public ViewController() {
        super();
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       // if (request.getServletPath().toString().equals("/")) {
       //     request.getRequestDispatcher("index.jsp").forward(request, response);
       // } else {
            Map<String, Command> commands = UIHelper.getMapCommands();
            Command cmdGenres = commands.get("allGenres");
            cmdGenres.execute(request, response);
            String action = request.getParameter("action");
            if (commands.containsKey(action)) {
                Command cmd = commands.get(action);
                String view = cmd.execute(request, response);
                request.getRequestDispatcher(view).forward(request, response);   
            } else {
                LOGGER.debug("Command not found.");
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }  
       //}
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }
    
    @Override
    public String getServletInfo() {
        return "eLibrary";
    }

}
